<template>
  <div class="base-container">
    <t-row :gutter="13">
      <!-- <t-col :span="2" style="padding-right: 10px">
        <div style="display: flex;font-weight: bold;font-size: 30px;padding: 30px">
          学科分类
        </div>
        <t-input
          style="margin-bottom: 10px"
          clearable
          placeholder="请输入学科分类"
          v-model="systemIdName"
          @change="deptNameTreeFilter"
        >
          <template #prefix-icon>
            <t-icon name="search" class="icon" size="16"/>
          </template>
        </t-input>
        <t-tree checkable activable @change="onChange" :expandLevel="2" v-model="queryParams.systemIds" checkStrictly :filter="filterByText" :data="standardSystemTree" :keys="{value:'id'}"   :expandAll="false"  hover :expand-on-click-node="false"  />
      </t-col> -->
      <!-- <t-col :span="2">
        <div style="display: flex;font-weight: bold;font-size: 30px;padding: 30px">
          学科分类
        </div>
        <t-tree checkable activable @change="onChange" :expandLevel="2" v-model="queryParams.systemIds" checkStrictly :data="standardSystemTree" :keys="{value:'id'}"   :expandAll="false"  hover :expand-on-click-node="false"  />
      </t-col> -->
      <t-col :span="12">
        <div style="display: flex;font-weight: bold;justify-content: center;font-size: 30px;padding: 30px">
          待形式审查项目列表
        </div>
        <t-tabs  @change="changeTab" v-model="queryParams.xsReviewType" style="margin-bottom: 10px">
          <t-tab-panel :key="item.id" :value="item.id" v-for="(item) in projectCategoryOptions" :label="item.name" :destroyOnHide="false">
          </t-tab-panel>
        </t-tabs>
        <t-table maxHeight="400"  row-key="approveId"   :columns="columns" :data="data"
                 :selected-row-keys="selectedRowKeys"
                 :loading="dataLoading"
                 @select-change="(val)=>{selectedRowKeys=val}">
          <template #[`projectNum`]="{ row }">
            <div v-if="row.projectNum">
              {{row.projectNum}}
            </div>
            <div v-else>
              暂未分配
            </div>
          </template>
          <template #projectName="{ row }">
            <t-link  @click="handleByAllDetails(row)" hover="color" theme="primary">{{row.projectName}}</t-link>
          </template>
          <template #[`subjectClassification`]="{row}">
            {{ row.subjectClassification | filterByDict(standardSystemTree) }}
          </template>
           <template #standardProperty="{ row }">
        {{ row.standardProperty | filterByDict(dict.type.standard_property) }}
      </template>

        <template #formulateType="{ row }">
         {{ row.formulateType | filterByDict(dict.type.formulate_type) }} <span v-if="row.formulateType!=='1'">({{ row.reviseNum }})</span>
        </template>

        <template #draftUnitNames="{ row }">
        <t-tooltip :content="row.draftUnitNames">
          <p style="display: -webkit-box; -webkit-box-orient: vertical; -webkit-line-clamp: 2; text-overflow: ellipsis; overflow: hidden;">
            {{row.draftUnitNames || "-"}}
          </p>
        </t-tooltip>
      </template>

        <template #projectUp="{ row }">
        {{ row.projectUp === '1'?'是':'否' }}
      </template>
      <template #patentUp="{ row }">
        {{ row.patentUp === '1'?'是':'否' }}
      </template>
       <template #xsReviewStatus="{ row }">
            <t-tag v-if="row.xsReviewStatus" @click="dialog.header=row.projectName;dialog.objId=row.id;dialog.open_approve_list=true" class="cursor-pointer" :theme="handleTheme(row.xsReviewStatus, dict.type.xs_review_status)" variant="light">
              {{ row.xsReviewStatus | filterByDict(dict.type.xs_review_status) }}
            </t-tag>
            <t-tag  class="cursor-pointer" v-else @click="dialog.header=row.projectName;dialog.objId=row.id;dialog.open_approve_list=true" theme="warning" variant="light">未评审</t-tag>
          </template>
    <template #standardStatus="{ row }">
        <t-tag   @click="dialog.header=row.projectName;dialog.objId=row.id;dialog.open_approve_list=true"   class="cursor-pointer" :theme="handleTheme(row.standardStatus, dict.type.standard_status)" variant="light">
          {{ row.standardStatus | filterByDict(dict.type.standard_status) }}
        </t-tag>
      </template>
          <template #op="{row}">
            <t-button  @click="handleByDetails(row)"
                      size="small" variant="text" class="t-button-link">
              <t-icon name="info-circle" slot="icon"/>
              详情
            </t-button>
          </template>
        </t-table>
        <div style="display: flex;font-weight: bold;justify-content: center;gap:10px;margin-top:30px">
          <t-button :disabled="this.selectedRowKeys.length<=0" @click="joinList" size="large" theme="default" variant="outline"> <t-icon name="arrow-down" slot="icon"></t-icon>分配</t-button>
          <t-button :disabled="this.selectedRowKeys2.length<=0" @click="removeList" size="large" theme="default" variant="outline"> <t-icon name="arrow-up" slot="icon"></t-icon>移出</t-button>
          <t-button size="large" @click="onSubmit" theme="primary" :loading="applyLoading">{{ applyLoading?'提交中...':'点击提交' }}</t-button>
        </div>
        <div style="display: flex;font-weight: bold;justify-content: center;font-size: 30px;padding: 30px">
          已分配项目列表
        </div>
        <t-table maxHeight="400" row-key="approveId"   :columns="columns2" :data="data2" :selected-row-keys="selectedRowKeys2"
                 :loading="dataLoading2"
                 @select-change="(val)=>{selectedRowKeys2=val}">
          <template #[`projectName`]="{ row }">
            <t-link  @click="handleByAllDetails(row)" hover="color" theme="primary">{{row.projectName}}</t-link>
           
          </template>
          <template #[`subjectClassification`]="{row}">
            {{ row.subjectClassification | filterByDict(standardSystemTree) }}
          </template>
               <template #standardProperty="{ row }">
        {{ row.standardProperty | filterByDict(dict.type.standard_property) }}
      </template>

        <template #formulateType="{ row }">
         {{ row.formulateType | filterByDict(dict.type.formulate_type) }} <span v-if="row.formulateType!=='1'">({{ row.reviseNum }})</span>
        </template>

        <template #draftUnitNames="{ row }">
        <t-tooltip :content="row.draftUnitNames">
          <p style="display: -webkit-box; -webkit-box-orient: vertical; -webkit-line-clamp: 2; text-overflow: ellipsis; overflow: hidden;">
            {{row.draftUnitNames || "-"}}
          </p>
        </t-tooltip>
      </template>

        <template #projectUp="{ row }">
        {{ row.projectUp === '1'?'是':'否' }}
      </template>
      <template #patentUp="{ row }">
        {{ row.patentUp === '1'?'是':'否' }}
      </template>
       <template #xsReviewStatus="{ row }">
            <t-tag v-if="row.xsReviewStatus" @click="dialog.header=row.projectName;dialog.objId=row.id;dialog.open_approve_list=true" class="cursor-pointer" :theme="handleTheme(row.xsReviewStatus, dict.type.xs_review_status)" variant="light">
              {{ row.xsReviewStatus | filterByDict(dict.type.xs_review_status) }}
            </t-tag>
            <t-tag  class="cursor-pointer" v-else @click="dialog.header=row.projectName;dialog.objId=row.id;dialog.open_approve_list=true" theme="warning" variant="light">未评审</t-tag>
          </template>
    <template #standardStatus="{ row }">
        <t-tag  @click="dialog.header=row.projectName;dialog.objId=row.id;dialog.open_approve_list=true"   class="cursor-pointer" :theme="handleTheme(row.standardStatus, dict.type.standard_status)" variant="light">
          {{ row.standardStatus | filterByDict(dict.type.standard_status) }}
        </t-tag>
      </template>
          <template #op="{row}">
            <t-button  @click="handleByDetails(row)"
                      size="small" variant="text" class="t-button-link">
              <t-icon name="info-circle" slot="icon"/>
              详情
            </t-button>
          </template>
        </t-table>
      </t-col>
    </t-row>
      <standardDetailDialog :tabDefaultValue="tabDefaultValue" :header="dialog.header" :objId="dialog.objId" :visible.sync="dialog.open_standard_detail" v-if="dialog.open_standard_detail">
    </standardDetailDialog>
    <!-- 申报书 -->
    <apply-detail-dialog :obj-id="dialog.objId" :header="dialog.header" :visible.sync="dialog.open_detail_a" v-if="dialog.open_detail_a" ></apply-detail-dialog>
    <!-- 申报表 -->
      <report-detail-dialog :obj-id="dialog.objId" :header="dialog.header" :visible.sync="dialog.open_detail_b" v-if="dialog.open_detail_b" ></report-detail-dialog>
    <!-- 报批表 -->
       <submit-detail-dialog :obj-id="dialog.objId" :header="dialog.header" :visible.sync="dialog.open_detail_c" v-if="dialog.open_detail_c" ></submit-detail-dialog>
    <approve-list :header="dialog.header" :objId="dialog.objId" :visible.sync="dialog.open_approve_list"
                  v-if="dialog.open_approve_list"></approve-list>
  </div>
</template>

<script>
import ApproveList from "./components/approve-list.vue";
import standardDetailDialog from "@/pages/bzh/standard/components/standard-detail-dialog.vue";
import applyDetailDialog from "@/pages/bzh/apply/components/apply-detail-dialog.vue";
import reportDetailDialog from "@/pages/bzh/report/components/report-detail-dialog.vue";
import submitDetailDialog from "@/pages/bzh/submit/components/submit-detail-dialog.vue";

export default {
  name: "select-project",
  dicts: ["standard_property","formulate_type","standard_status","xs_review_status"],
  components: {
    ApproveList,
    standardDetailDialog,
    applyDetailDialog,
    reportDetailDialog,
    submitDetailDialog
  },
  data() {
    return {
      userId: null,
      site_tag: import.meta.env.VITE_SITE_TAG,
      tabDefaultValue:"2",
      applyLoading: false,
      data2: [],
      dataLoading2: false,
      selectedRowKeys2: [],
      projectCategoryOptions: [
        // {id: null, name:"全部" },
        {id: "0", name:"建议表形式审查" },
        {id: "1" , name:"申报书形式审查" },
        {id: "2" , name:"报审表形式审查" },
        {id: "3" , name:"报批表形式审查" }
      ],
      systemIdName:"",
      filterByText: null,
      dialog: {
        header: "",
        objId: 0,
        open_approve_list: false,
        open_standard_detail:false,
        open_detail_a:false,
        open_detail_b:false,
        open_detail_c:false,
      },
      selectedRowKeys: [],
      queryParams: {
        reviewType: '',
        pageNum: 1,
        pageSize: 10,
        dateRange: [],
        systemIds: [],
        isAddReview: '0',
        xsReviewType: "0",
      },
      data: [],
      dataLoading: false,
      pagination: {
        defaultCurrent: 1,
        defaultPageSize: 10,
        total: 0,
        showPageSize: false,
        showFirstAndLastPageBtn: false,
      },
      standardSystemTree:undefined,
      columns:[
        {
          colKey: 'row-select',
          type: 'multiple',
          width: 64,
        },
        {
          colKey: "projectName",
          title: "标准名称",
          align: "center",
          width: 220
        },
        {
          colKey: "standardProperty",
          title: "标准性质",
          align: "center",
        },
        {
          colKey: "formulateType",
          title: "制定/修订",
          align: "center",
          width: 100
        },
        {
          colKey: "manageDeptName",
          title: "主管部门",
          align: "center",
          width: 180,
        },
        {
          colKey: "draftUnitNames",
          title: "起草单位",
          align: "center",
          width: 180,
        },
        {
          colKey: "subjectClassification",
          title: "学科分类",
          align: "center",
          width: 100
        },
        {
          colKey: "completeDate",
          title: "计划完成时间",
          align: "center",
          width: 130,
          sorter: true,
        },
        {
          colKey: "projectUp",
          title: "有项目支撑",
          align: "center",
          width: 100
        },
        {
          colKey: "patentUp",
          title: "有涉及专利",
          align: "center",
          width: 100
        },
        {
          colKey: "createTime",
          title: "创建时间",
          align: "center",
          width: 200
        },
        {
          colKey: "standardStatus",
          title: "标准状态",
          align: "center",
          width: 160,
          fixed: 'right'
        },
        {
          colKey: "xsReviewStatus",
          title: "标委会审批状态 ",
          align: "center",
          width: 160,
          fixed: 'right'
        },
        {
          colKey: "op",
          title: "操作",
          align: "center",
          width: 120,
          fixed: 'right'
        },
      ],
      columns2:[],
      visible: true,
    }
  },
  async created() {
    this.columns2 = this.columns.map((cItem,cIndex) => {
      if(!cIndex) {
        return {...cItem,
          disabled:({row}) => row.xsReviewStatus === '3'
        }
      }
      return cItem
      
    })
    const userId = this.$route.params && this.$route.params.userId;
    if (!userId) {
      this.$message.error("用户id丢失返回");
      this.$router.push("/bzh/approve/approver-management");
    }
    this.userId = userId;
    this.getList();
    this.getBindList();
    this.getStandardSystemTree()
  },
  methods: {
    getStandardSystemTree() {
      this.$api.bzh.standard.standardSystemTree().then(res => {
        this.standardSystemTree =res.data
      }).catch(e => {
        this.$message.error(e.toString());
      })
    },
    changeTab(value){
      this.queryParams.xsReviewType = value;
      this.getList();
      this.getBindList()
    },
    onChange(val){
      this.queryParams.systemIds = val;
      this.getList();
    },
    joinList(){
      const newData = []
      this.data.forEach((val,index) => {
        if(this.selectedRowKeys.includes(val.approveId)){
          newData.push({...val,rowIndex:index})
        }
      })
      this.data = this.data.filter(val=>{
        if(this.selectedRowKeys.includes(val.approveId)){
          return false
        }
        return true
      })
      this.data2.push(...newData)
      this.selectedRowKeys = []
      
    },
    removeList(){
      const newData = []
      this.data2.forEach((val,index) => {
        if(this.selectedRowKeys2.includes(val.approveId)){
          newData.push(val)
        }
      })
      this.data2 = this.data2.filter(val=>{
        if(this.selectedRowKeys2.includes(val.approveId)){
          return false
        }
        return true
      })
      this.data.push(...newData)
      this.selectedRowKeys2 = []
    },
    getBindList() {
      this.dataLoading2 = true;
      this.$api.bzh.approve.getApproverReviewByUserId(this.userId,this.queryParams.xsReviewType).then((res) => {
        this.data2 = res.data;
        this.dataLoading2 = false;
      }).catch((e) => {
        this.dataLoading2 = false
        this.$message.error(e.toString());
      });
    },
    getList() {
      this.dataLoading = true;
      this.queryParams.pageSize = 1000000;
      this.$api.bzh.approve.getApproverReviewAllList2(this.queryParams).then(response => {
        // this.pagination.total = response.total;
        this.data = response.rows;
        console.log(this.data)
        this.dataLoading = false;
      }).catch((e) => {
        this.dataLoading = false;
        this.$message.error(e.toString());
      });
    },
    onSubmit() {
      this.applyLoading = true;
      const beforeFiltering = this.data2.filter(cItem => cItem.xsReviewStatus !== '3').map(val=> val.id)
      const ids = Array.from(new Set(beforeFiltering))
      this.$api.bzh.approve.addReviewProject({
        approverId: this.userId,
        xsReviewType:this.queryParams.xsReviewType,
        localIds: ids
      }).then((res) => {
        // 初始化
        this.$message.success("分配成功");
        this.applyLoading = false;
        this.getList();
        this.getBindList();
      }).catch((e) => {
        this.$message.error(e.toString());
        this.applyLoading = false;
      });
    },
    handleByDetails(row){
      this.dialog.header=row.projectName
      this.dialog.objId=row.id
      const xsReviewType  = Number(this.queryParams.xsReviewType)
      switch (xsReviewType) {  
      case 1:  
        this.dialog.open_detail_a =true
        break;  
      case 2: 
        this.dialog.open_detail_b =true
        break;  
      case 3:  
        this.dialog.open_detail_b =true
        break;  
      default:  
        this.dialog.open_detail_a =true
      }
    },
    handleByAllDetails(row){
      const xsReviewType  = Number(this.queryParams.xsReviewType)
      switch (xsReviewType) {  
      case 1:  
        this.tabDefaultValue = "2"
        break;  
      case 2: 
        this.tabDefaultValue = "4"
        break;  
      case 3:  
        this.tabDefaultValue = "5"
        break;  
      default:  
        this.tabDefaultValue = "2"
      }
      this.dialog.objId=row.id
      this.dialog.header=row.projectName
      this.dialog.open_standard_detail=true
    },
    closeDialog() {
      // this.$emit("update:visible", false);
    },
    deptNameTreeFilter(){
      if (this.systemIdName) {
        // 存在过滤文案，才启用过滤
        this.filterByText = (node) => {
          const rs = node.data.label.indexOf(this.systemIdName) >= 0;
          // 命中的节点会强制展示
          // 命中节点的路径节点会锁定展示
          // 未命中的节点会隐藏
          return rs;
        };
      } else {
        // 过滤文案为空，则还原 tree 为无过滤状态
        this.filterByText = null;
      }
    },
  }
}
</script>

<style scoped>
.overlay-options {
  display: inline-block;
  font-size: 20px;
}
</style>
